package com.ksyzt.ksite2.client.orgnization;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;
import com.ksyzt.gwt.client.common.FlashMessageComposite;
import com.ksyzt.gwt.client.common.GwtUtil;
import com.ksyzt.gwt.client.event.MessageEvent;
import com.ksyzt.gwt.client.event.MessageHandler;
import com.ksyzt.gwt.client.mainframe.AppData;
import com.ksyzt.gwt.client.mainframe.IAppModule;
import com.ksyzt.gwt.client.mainframe.ModuleProperties;
import com.ksyzt.gwt.client.ui.richeditor.SimpleClickEditor;
import com.ksyzt.ksite2.client.common.ServerProxy;
import com.ksyzt.ksite2.shared.OrgType;
import com.ksyzt.ksite2.shared.SysConst;
import com.ksyzt.ksite2.shared.modle.ORGANIZATIONObj;

public class OrgnizationEditor extends FlashMessageComposite implements
		RequiresResize, IAppModule {

	private static OrgnizationEditorUiBinder uiBinder = GWT
			.create(OrgnizationEditorUiBinder.class);

	interface OrgnizationEditorUiBinder extends
			UiBinder<Widget, OrgnizationEditor> {
	}

	public OrgnizationEditor() {
		initWidget(uiBinder.createAndBindUi(this));
		btnSave.setEnabled(false);
		btnCreateChild.setEnabled(false);

		tree.addMessageHandler(m_tree_handler);
		tree.setSize("100%", "100%");
	}

	boolean m_onlyone;

	public void initData(int userid, int orgtype, boolean onlyone) {
		m_userid = userid;
		m_orgtype = orgtype;
		m_onlyone = onlyone;
		tree.initTree(m_userid, m_orgtype, OrgType.getOrgNameByType(m_orgtype),
				onlyone);
		sureCanDelete();
	}

	MessageHandler m_tree_handler = new MessageHandler() {

		public void onMessage(Object sender, Integer message, Object value) {
			if (MessageEvent.CREATEROOT.equals(message)) {
				edit(m_userid, m_orgtype, null, null, null);
			} else if (MessageEvent.ITEMCLICK.equals(message)) {
				TreeItem ti = (TreeItem) value;
				ORGANIZATIONObj o = (ORGANIZATIONObj) ti.getUserObject();

				ORGANIZATIONObj p = null;
				TreeItem tip = tree.getTreeItem(o.getPID());

				if (tip != null && tip.getUserObject() != null) {
					p = (ORGANIZATIONObj) tip.getUserObject();
				}

				edit(m_userid, m_orgtype, ti, p, o);
			}

		}
	};

	@UiField
	OrgnizationTree tree;
	@UiField
	TextBox txtName;
	@UiField
	TextBox txtRank;
	@UiField
	SimpleClickEditor txtDesc;

	@UiField
	Label lbID;
	@UiField
	Button btnSave;
	@UiField
	Button btnCreateChild;

	ORGANIZATIONObj m_org;
	ORGANIZATIONObj m_parent;
	TreeItem m_treeitem;
	int m_userid;
	int m_orgtype;

	/**
	 * 编辑组织树
	 * 
	 * @param userid
	 *            组织所属用户
	 * @param orgtype
	 *            组织类型
	 * @param treeitem
	 *            组织树节点
	 * @param parent
	 *            父节点
	 * @param org
	 *            当前编辑的组织
	 */
	public void edit(int userid, int orgtype, TreeItem treeitem,
			ORGANIZATIONObj parent, ORGANIZATIONObj org) {
		message("");
		showflash();
		m_orgtype = orgtype;
		m_userid = userid;
		m_treeitem = treeitem;
		m_org = org;
		m_parent = parent;

		if (m_org != null) {
			txtName.setValue(m_org.getNAME());
			txtRank.setValue(m_org.getRANKVAL().toString());

			txtDesc.setValue(m_org.getDESCRIPTION());

			btnCreateChild.setEnabled(true);
			btnSave.setEnabled(true);
			lbID.setText("编辑组织架构节点:" + m_org.getID());

			sureCanDelete();

			showPicture(strImagepath, m_org.getID());

		} else {
			showPicture(strImagepath, null);
			txtName.setValue("");
			txtRank.setValue("0");

			txtDesc.setValue("");

			btnCreateChild.setEnabled(false);
			btnSave.setEnabled(true);

			lbID.setText("新建组织架构节点");

		}

	}

	@UiHandler("btnCreateChild")
	void onCreateChild(ClickEvent e) {
		edit(m_userid, m_orgtype, null, m_org, null);
	}

	@UiHandler("btnSave")
	void onSave(ClickEvent e) {
		if (m_org == null) {
			ORGANIZATIONObj o = new ORGANIZATIONObj();

			if (m_parent == null) {
				o.setNAME(txtName.getValue());

				o.setDESCRIPTION(txtDesc.getValue());
				o.setRANKVAL(Integer.valueOf(txtRank.getValue()));
				o.setPID(-1);
				o.setOTYPE(m_orgtype);
				o.setROOTID(-1);
				o.setWHOID(m_userid);

				ServerProxy.SYS_MANAGER.modifyOrganization(o, m_modify_handler);
			} else {
				// o.setTAG(txtTag.getValue());
				o.setNAME(txtName.getValue());
				// o.setURL(txtURL.getValue());
				o.setDESCRIPTION(txtDesc.getValue());
				o.setRANKVAL(Integer.valueOf(txtRank.getValue()));
				o.setPID(m_parent.getID());
				o.setOTYPE(m_orgtype);
				// o.setCODE(txtCode.getValue());
				// o.setDISPLAY(checkDisply.getValue() == true ? 1 : 0);
				// o.setUSERVALUE(txtBBSID.getValue());
				// o.setCSS(txtCSS.getValue());
				if (m_parent.getROOTID() == -1) {
					o.setROOTID(m_parent.getID());
				} else {
					o.setROOTID(m_parent.getROOTID());
				}

				o.setWHOID(m_userid);
				ServerProxy.SYS_MANAGER.modifyOrganization(o, m_modify_handler);
			}
		} else {
			// m_org.setTAG(txtTag.getValue());
			m_org.setNAME(txtName.getValue());
			// m_org.setURL(txtURL.getValue());
			m_org.setDESCRIPTION(txtDesc.getValue());
			m_org.setRANKVAL(Integer.valueOf(txtRank.getValue()));
			// m_org.setCODE(txtCode.getValue());
			// m_org.setDISPLAY(checkDisply.getValue() == true ? 1 : 0);
			// m_org.setUSERVALUE(txtBBSID.getValue());
			// m_org.setCSS(txtCSS.getValue());
			ServerProxy.SYS_MANAGER.modifyOrganization(m_org, m_modify_handler);
		}
	}

	AsyncCallback<ORGANIZATIONObj> m_modify_handler = new AsyncCallback<ORGANIZATIONObj>() {

		public void onSuccess(ORGANIZATIONObj result) {
			tree.initTree(m_userid, m_orgtype,
					OrgType.getOrgNameByType(m_orgtype), m_onlyone);
		}

		public void onFailure(Throwable caught) {

			Window.alert(caught.getMessage());
		}
	};
	private boolean m_candelete = false;

	public void EnabledDelete(Boolean b) {
		m_candelete = b;
		sureCanDelete();
	}

	/**
	 * 确定删除按钮可用
	 */
	void sureCanDelete() {
		if (m_candelete && m_org != null) {
			btnDelete.setEnabled(true);
		} else {
			btnDelete.setEnabled(false);
		}
	}

	// ////////////////////////////////////////////////////////消息显示
	@UiField
	Label lbMessage;

	// ////////////////////////////////////////////////////////删除节点
	@UiField
	Button btnDelete;
	private AsyncCallback<Boolean> on_delete_handler = new AsyncCallback<Boolean>() {

		public void onSuccess(Boolean result) {

			initData(m_userid, m_orgtype, m_onlyone);
			edit(m_userid, m_orgtype, null, null, null);
			sureCanDelete();
			message("删除成功");
		}

		public void onFailure(Throwable caught) {
			message(caught.getMessage());
		}
	};

	@UiHandler("btnDelete")
	void onDelete(ClickEvent e) {
		if (m_org != null && m_org.getID() != null) {
			ServerProxy.SYS_MANAGER.deleteOrganization(m_org.getID(),
					on_delete_handler);
		}

	}

	public void fireUpdate() {
		MessageEvent e = new MessageEvent(MessageEvent.UPDATE, 0);
		fireEvent(e);
	}

	@UiField
	HTMLPanel placeholder;

	@Override
	protected void onSaveImage(String json) {

		String[] r = GwtUtil.parsePostImageResult(json);
		String rcode = r[0];
		String message = r[1];
		if (rcode.equals("1")) {
			message(SysConst.MSG_UPLOAD_IMAGE_SUCCESS);
			if (m_org != null) {
				m_org.setICON(message);
				ServerProxy.SYS_MANAGER.modifyOrganization(m_org,
						m_modify_handler);
			}
			fireUpdate();
		} else {
			message(message);
		}
	}

	@Override
	protected void onShowFlash() {
		int left = placeholder.getAbsoluteLeft() + 10;
		int top = placeholder.getAbsoluteTop() + 10;
		moveFlashTo(left, top);
	}

	final public static String tag = "OrgnizationEditor";
	final public static String strImagepath = "images/orgpic";

	@Override
	public void onResize() {
		showflash();
	}

	HandlerRegistration handler;

	public static String KEY_ORGTYPE = "key_orgtype";
	public static String KEY_ONLYONE = "key_only";

	@Override
	public void onInitialize(AppData application, ModuleProperties pros) {
		handler = this.addMessageHandler(application.messageHandler);
		if (pros != null) {
			// initData(int userid, int orgtype, boolean onlyone)
			int userid = application.user.id;
			int orgtype = pros.getInt(KEY_ORGTYPE, OrgType.OT_ORGNIZATION);
			boolean onlyone = pros.getBoolean(KEY_ONLYONE, true);
			initData(userid, orgtype, onlyone);
		}
	}

	@Override
	public void onUnInitialize() {
		handler.removeHandler();
	}

	@Override
	public Widget getRootWidget() {
		return this;
	}
}
